<template> 
  <div class="world-map-container">
    <!-- 地图标题 -->
    <div class="map-header">
      <h3 class="text-lg font-bold text-white mb-4">{{ ts('全球政策分布', '全球政策分布') }}</h3>
    </div>
    
    <!-- 地图内容 -->
    <div class="map-content">
      <div 
        ref="worldMap" 
        class="world-map-chart"
        @mouseleave="handleMouseLeave"
      ></div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner"></div>
        <p class="loading-text">{{ ts('正在加载世界地图数据...', '正在加载世界地图数据...') }}</p>
      </div>
    </div>
    
    <!-- 国家详情弹窗 -->
    <div 
      v-if="selectedCountry && showTooltip" 
      class="country-detail"
      :style="{ left: tooltipX + 'px', top: tooltipY + 'px' }"
    >
      <div class="detail-header">
        <h4>{{ selectedCountry }}</h4>
        <button @click="closeTooltip" class="close-btn">×</button>
      </div>
      <div class="detail-content">
        <p>{{ ts('政策总数', '政策总数') }}: {{ selectedCountryData?.count?.toLocaleString() || 0 }}</p>
        <p>{{ ts('贸易额', '贸易额') }}: {{ selectedCountryData?.tradeVolume || ts('暂无数据', '暂无数据') }}</p>
        <p>{{ ts('企业数量', '企业数量') }}: {{ selectedCountryData?.companies || ts('暂无数据', '暂无数据') }}</p>
        <p>{{ ts('活跃度', '活跃度') }}: {{ selectedCountryData?.activity || ts('中等', '中等') }}</p>
        <p>{{ ts('更新时间', '更新时间') }}: {{ selectedCountryData?.updateTime || '2024-01-15' }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { useTranslation } from '../composables/useTranslation.js'

export default {
  name: 'WorldMapSVG',
  props: {
    viewMode: {
      type: String,
      default: 'trade'
    },
    showRoutes: {
      type: Boolean,
      default: true
    },
    highlightRegions: {
      type: Array,
      default: () => []
    }
  },
  emits: ['region-click', 'route-click'],
  setup() {
    // 使用翻译系统
    const { ts } = useTranslation()

    return {
      ts
    }
  },
  data() {
    return {
      chart: null,
      loading: true,
      selectedCountry: null,
      showTooltip: false,
      tooltipX: 0,
      tooltipY: 0,
      worldData: {
        'China': { count: 28470, activity: '极高', updateTime: '2024-01-15', tradeVolume: '4.6万亿', companies: '245万' },
        'United States': { count: 19340, activity: '极高', updateTime: '2024-01-14', tradeVolume: '4.9万亿', companies: '198万' },
        'Germany': { count: 8920, activity: '高', updateTime: '2024-01-13', tradeVolume: '1.8万亿', companies: '89万' },
        'Japan': { count: 7340, activity: '高', updateTime: '2024-01-12', tradeVolume: '1.2万亿', companies: '73万' },
        'United Kingdom': { count: 6230, activity: '高', updateTime: '2024-01-11', tradeVolume: '0.9万亿', companies: '62万' },
        'France': { count: 5670, activity: '高', updateTime: '2024-01-10', tradeVolume: '0.8万亿', companies: '56万' },
        'Italy': { count: 4890, activity: '中', updateTime: '2024-01-09', tradeVolume: '0.7万亿', companies: '48万' },
        'Canada': { count: 4560, activity: '中', updateTime: '2024-01-09', tradeVolume: '0.6万亿', companies: '45万' },
        'India': { count: 4200, activity: '中', updateTime: '2024-01-08', tradeVolume: '0.9万亿', companies: '42万' },
        'South Korea': { count: 3980, activity: '中', updateTime: '2024-01-08', tradeVolume: '0.7万亿', companies: '39万' },
        'Australia': { count: 3890, activity: '中', updateTime: '2024-01-08', tradeVolume: '0.4万亿', companies: '38万' },
        'Brazil': { count: 3450, activity: '中', updateTime: '2024-01-07', tradeVolume: '0.4万亿', companies: '34万' },
        'Russia': { count: 3200, activity: '中', updateTime: '2024-01-07', tradeVolume: '0.5万亿', companies: '32万' },
        'Spain': { count: 2890, activity: '中', updateTime: '2024-01-06', tradeVolume: '0.5万亿', companies: '28万' },
        'Netherlands': { count: 2560, activity: '中', updateTime: '2024-01-06', tradeVolume: '0.8万亿', companies: '25万' },
        'Singapore': { count: 2340, activity: '中', updateTime: '2024-01-05', tradeVolume: '0.7万亿', companies: '23万' },
        'Mexico': { count: 2100, activity: '中', updateTime: '2024-01-05', tradeVolume: '0.5万亿', companies: '21万' },
        'Indonesia': { count: 1890, activity: '低', updateTime: '2024-01-04', tradeVolume: '0.4万亿', companies: '18万' },
        'Thailand': { count: 1650, activity: '低', updateTime: '2024-01-04', tradeVolume: '0.3万亿', companies: '16万' },
        'Vietnam': { count: 1420, activity: '低', updateTime: '2024-01-03', tradeVolume: '0.6万亿', companies: '14万' },
        'Malaysia': { count: 1200, activity: '低', updateTime: '2024-01-03', tradeVolume: '0.4万亿', companies: '12万' },
        'Turkey': { count: 1150, activity: '低', updateTime: '2024-01-02', tradeVolume: '0.4万亿', companies: '11万' },
        'Saudi Arabia': { count: 980, activity: '低', updateTime: '2024-01-02', tradeVolume: '0.5万亿', companies: '9万' },
        'UAE': { count: 890, activity: '低', updateTime: '2024-01-01', tradeVolume: '0.5万亿', companies: '8万' },
        'Poland': { count: 780, activity: '低', updateTime: '2024-01-01', tradeVolume: '0.3万亿', companies: '7万' },
        'Belgium': { count: 650, activity: '低', updateTime: '2023-12-31', tradeVolume: '0.4万亿', companies: '6万' },
        'Sweden': { count: 560, activity: '低', updateTime: '2023-12-31', tradeVolume: '0.2万亿', companies: '5万' },
        'Switzerland': { count: 450, activity: '低', updateTime: '2023-12-30', tradeVolume: '0.3万亿', companies: '4万' },
        'Norway': { count: 380, activity: '低', updateTime: '2023-12-30', tradeVolume: '0.2万亿', companies: '3万' },
        'Chile': { count: 320, activity: '低', updateTime: '2023-12-29', tradeVolume: '0.1万亿', companies: '3万' }
      }
    }
  },
  computed: {
    selectedCountryData() {
      return this.worldData[this.selectedCountry]
    }
  },
  mounted() {
    this.initMap()
  },
  beforeUnmount() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    async initMap() {
      try {
        const echarts = await this.loadECharts()
        const worldGeoData = await this.loadWorldMapData()
        echarts.registerMap('world', worldGeoData)
        this.chart = echarts.init(this.$refs.worldMap, 'dark')
        const option = this.getMapOption()
        this.chart.setOption(option)
        this.bindEvents()
        this.loading = false
      } catch (error) {
        console.error('世界地图初始化失败:', error)
        this.loading = false
      }
    },
    
    async loadECharts() {
      return new Promise((resolve, reject) => {
        if (window.echarts) {
          resolve(window.echarts)
          return
        }
        const script = document.createElement('script')
        script.src = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/5.5.0/echarts.min.js'
        script.onload = () => resolve(window.echarts)
        script.onerror = reject
        document.head.appendChild(script)
      })
    },
    
    async loadWorldMapData() {
    try {
      const response = await fetch('https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson')
      if (!response.ok) throw new Error('Failed to load world map data')
      return await response.json()
    } catch (error) {
      console.error('加载世界地图数据失败:', error)
      return this.getSimpleWorldData()
    }
  },
    
    getSimpleWorldData() {
      return { type: "FeatureCollection", features: [] }
    },
    
    getMapOption() {
      const mapData = Object.keys(this.worldData).map(name => ({
        name,
        value: this.worldData[name].count
      }))
      return {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            const data = this.worldData[params.name]
            if (!data) return `${params.name}<br/>${this.ts('暂无数据', '暂无数据')}`
            return `
              <div style="padding: 8px; min-width: 240px;">
                <div style="font-weight: bold; color: #00f5ff; margin-bottom: 8px; font-size: 14px;">${params.name}</div>
                <div style="margin-bottom: 4px;">${this.ts('政策总数', '政策总数')}: <span style="color: #00f5ff; font-weight: bold;">${data.count.toLocaleString()}</span></div>
                <div style="margin-bottom: 4px;">${this.ts('贸易额', '贸易额')}: <span style="color: #10b981;">${data.tradeVolume}</span></div>
                <div style="margin-bottom: 4px;">${this.ts('企业数量', '企业数量')}: <span style="color: #f59e0b;">${data.companies}</span></div>
                <div style="margin-bottom: 4px;">${this.ts('活跃度', '活跃度')}: <span style="color: ${
                  data.activity === '极高' ? '#ef4444' : 
                  data.activity === '高' ? '#f97316' :
                  data.activity === '中' ? '#eab308' : '#6b7280'
                }">${this.ts(data.activity, data.activity)}</span></div>
                <div style="font-size: 11px; color: #9ca3af;">${this.ts('更新时间', '更新时间')}: ${data.updateTime}</div>
              </div>
            `
          },
          backgroundColor: 'rgba(15, 23, 42, 0.95)',
          borderColor: 'rgba(0, 245, 255, 0.3)',
          borderWidth: 1,
          textStyle: { color: '#e2e8f0', fontSize: 12 }
        },
        visualMap: {
          min: 0,
          max: 30000,
          left: 'left',
          top: 'bottom',
          text: [this.ts('极高', '极高'), this.ts('低', '低')],
          realtime: false,
          calculable: true,
          inRange: { 
            color: ['#0f172a', '#1e3a8a', '#3b82f6', '#60a5fa', '#93c5fd', '#bfdbfe', '#00f5ff'] 
          },
          textStyle: { color: '#e2e8f0', fontSize: 12 }
        },
        series: [
          {
            name: this.ts('政策分布', '政策分布'),
            type: 'map',
            map: 'world',
            roam: true,
            zoom: 1,
            scaleLimit: { min: 0.5, max: 3 },
            emphasis: {
              focus: 'self',
              itemStyle: {
                areaColor: '#00f5ff',
                borderColor: '#ffffff',
                borderWidth: 1,
                shadowColor: 'rgba(0, 245, 255, 0.8)',
                shadowBlur: 10
              },
              label: { show: true, color: '#000', fontSize: 10, fontWeight: 'bold' }
            },
            itemStyle: {
              borderColor: 'rgba(0, 245, 255, 0.3)',
              borderWidth: 0.5,
              shadowColor: 'rgba(0, 0, 0, 0.3)',
              shadowBlur: 2
            },
            label: { show: false, color: '#e2e8f0', fontSize: 8 },
            data: mapData
          }
        ]
      }
    },
    
    bindEvents() {
      this.chart.on('click', (params) => {
        if (params.componentType === 'series') {
          this.selectedCountry = params.name
          this.showTooltip = true
          this.updateTooltipPosition(params.event.event)
          // 发射区域点击事件
          this.$emit('region-click', {
            name: params.name,
            data: this.worldData[params.name]
          })
        }
      })
      this.chart.on('mousemove', (params) => {
        if (params.componentType === 'series') {
          this.updateTooltipPosition(params.event.event)
        }
      })
      window.addEventListener('resize', this.handleResize)
    },
    
    handleResize() {
      if (this.chart) this.chart.resize()
    },
    
    handleMouseLeave() {
      this.showTooltip = false
    },
    
    updateTooltipPosition(event) {
      const rect = this.$refs.worldMap.getBoundingClientRect()
      this.tooltipX = event.clientX - rect.left + 10
      this.tooltipY = event.clientY - rect.top - 10
    },
    
    closeTooltip() {
      this.showTooltip = false
      this.selectedCountry = null
    }
  }
}
</script>

<style scoped>
.world-map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.map-header {
  margin-bottom: 15px;
  padding: 16px 20px;
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px 8px 0 0;
}

.map-content {
  position: relative;
  width: 100%;
  height: calc(100% - 60px);
  min-height: 300px;
  background: transparent;
  border-radius: 0 0 8px 8px;
  overflow: hidden;
}

.world-map-chart {
  width: 100%;
  height: 100%;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(15, 23, 42, 0.9);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 2px solid rgba(0, 245, 255, 0.3);
  border-top: 2px solid #00f5ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

.loading-text {
  color: #00f5ff;
  font-size: 12px;
  margin: 0;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.country-detail {
  position: absolute;
  background: linear-gradient(135deg, rgba(15, 23, 42, 0.95) 0%, rgba(30, 41, 59, 0.95) 100%);
  border: 1px solid rgba(0, 245, 255, 0.3);
  border-radius: 6px;
  padding: 12px;
  min-width: 180px;
  z-index: 1000;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  pointer-events: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid rgba(0, 245, 255, 0.2);
}

.detail-header h4 {
  color: #00f5ff;
  margin: 0;
  font-size: 14px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: #94a3b8;
  font-size: 16px;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.detail-content p {
  margin: 6px 0;
  color: #e2e8f0;
  font-size: 12px;
  line-height: 1.4;
}

.detail-content p:first-child {
  color: #00f5ff;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .map-header {
    padding: 12px 16px;
  }
  
  .map-content {
    height: calc(100% - 50px);
    min-height: 250px;
  }
  
  .country-detail {
    max-width: 200px;
    font-size: 11px;
  }
}
</style>